﻿using Coding4Fun.MissionControl.API.Helpers;
using System;
using System.IO;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace Coding4Fun.MissionControl.API
{
    public class CoreStarter
    {
        static TcpListener listener;

        public static void LaunchSocket()
        {
            Console.WriteLine("Starting socket server on port {0}...", Constants.DEFAULT_PORT);

            listener = new TcpListener(NetworkHelper.GetLocalIPAddress(), Constants.DEFAULT_PORT);
            listener.Start();

            for (int i = 0; i < Constants.MAX_CONCURRENT_CLIENTS; i++)
            {
                Thread socketThread = new Thread(new ThreadStart(ListenForData));
                socketThread.Start();
            }
        }

        private static void ListenForData()
        {
            Console.WriteLine("Listener thread started.");

            while (true)
            {
                Socket acceptedSocket = listener.AcceptSocket();
                using (MemoryStream coreStream = new MemoryStream())
                {
                    try
                    {
                       
                        Console.WriteLine("Incoming connection: {0}", acceptedSocket.RemoteEndPoint);

                        using (Stream sourceStream = new NetworkStream(acceptedSocket))
                        {
                            sourceStream.ReadTimeout = Constants.SOCKET_READ_TIMEOUT;

                            byte[] buffer = new byte[Constants.DEFAULT_BUFFER_SIZE];
                            int i;

                            while ((i = sourceStream.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                coreStream.Write(buffer, 0, i);
                            }
                        }
                    }
                    catch
                    {
                        string data = Encoding.ASCII.GetString(coreStream.ToArray());
                        CommandHelper.InterpretCommand(data, acceptedSocket.RemoteEndPoint.ToString());
                    }
                }
            }
        }
    }
}
